<template>
  <el-header class="header">
    <div class="logo">学习助手</div>
    <div class="user-info" v-if="isLoggedIn">
      <el-dropdown @command="handleCommand">
        <span class="user-dropdown">
          {{ username }}
          <el-icon><ArrowDown /></el-icon>
        </span>
        
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">个人资料</el-dropdown-item>
            <el-dropdown-item command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-header>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()
const store = useStore()

// 使用计算属性获取 store 中的状态
const isLoggedIn = computed(() => store.getters.isLoggedIn)
const username = computed(() => store.getters.username)

const handleCommand = (command) => {
  if (command === 'logout') {
    store.dispatch('logout')
    ElMessage.success('已退出登录')
    router.push('/login')
  } else if (command === 'profile') {
    router.push('/profile')
  }
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-dropdown .el-icon {
  margin-left: 4px;
}
</style>